package com.yc.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/7/30
 * Email haijunzhou@hnit.edu.cn
 */
public class Demo1 {
    public static void main(String[] args) throws
            InstantiationException, // 构造函数执行错误
            IllegalAccessException, // 错误访问 例如:调用private方法
            NoSuchMethodException, // 没有该方法
            InvocationTargetException, // 方法执行异常
            NoSuchFieldException {  // 没有该属性
        Class<A> aClass = A.class;
        System.out.println("===========getFields=========");
        for (Field field : aClass.getFields()) {
            System.out.println(field);
        }
        System.out.println("===========getDeclaredFields=========");
        for (Field field : aClass.getDeclaredFields()) {
            System.out.println(field);
        }

        Class<B> bClass = B.class;
        System.out.println("===========B.getFields=========");
        for (Field field : bClass.getFields()) {
            System.out.println(field);
        }
        System.out.println("===========B.getDeclaredFields=========");
        for (Field field : bClass.getDeclaredFields()) {
            System.out.println(field);
        }

        System.out.println("********************************");


        Class cClass = C.class;
        // 如何一个类获取所有的属性?
        do{
            System.out.println("cClass = " + cClass + " 定义的属性");
            for (Field field : cClass.getDeclaredFields()) {
                System.out.println(field);
            }
            cClass = cClass.getSuperclass();
        } while(cClass!=null);

        System.out.println("********************************");
        // 获取属性值, 和执行对方法
        Object a = aClass.newInstance();  // 反射创建对象  new A();
        Field field = a.getClass().getDeclaredField("a");
        field.setAccessible(true); // 允许访问, 强制访问
        field.set(a, 100);   // a.a = 100;
        System.out.println(field.get(a));   // a.a

        System.out.println("********************************");
        Method hello = aClass.getDeclaredMethod("hello", String.class);
        hello.setAccessible(true);
        Object ret = hello.invoke(a, "张三");
        System.out.println("ret = " + ret);

    }
}

class A {
    private int a;
    protected String b;
    public Long c;

    char d;

    protected void test(){
        System.out.println("test");
    }

    private String hello(String name){
        System.out.println("hello " + name);
        return "ok";
    }

    private String hello(Integer name){
        System.out.println("hello " + name);
        return "ok";
    }

}

class B extends A{

    private int e;
    protected String f;
    public Long g;

    char h;

    public void demo(){
        System.out.println("demo");
    }
}

class C extends B{
    private int i;
}

